import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:netease_music/icons/my_flutter_app_icons.dart';
import 'package:netease_music/player/controller/bottom_player_overlay_controller.dart';
import 'package:netease_music/theme/custom_colors.dart';
import 'package:netease_music/theme/theme_controller.dart';
import 'package:netease_music/widget/badge_icon.dart';
import 'package:netease_music/pages/home/my_music/index.dart';
import 'package:netease_music/pages/home/person/index.dart';
import 'package:netease_music/pages/home/discover/index.dart';
import 'package:netease_music/widget/bottom_player_box.dart';
import 'package:netease_music/widget/build_item.dart';
import 'package:netease_music/widget/my_cached_network_image.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 添加 GlobalKey 用于访问 Scaffold 状态
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  // 底部音乐播放栏控制器
  final overlayController = Get.find<BottomPlayerOverlayController>();
  // 页面控制器
  final PageController _pageController = PageController();
  // 当前页面索引
  int _currentIndex = 0;
  // 页面内容
  final List<Widget> _pages = [
    // 发现
    const DisCover(),
    // 我的音乐
    const MyMusic(),
    // 与人相关
    const Person(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 添加 key 用于控制抽屉
      key: _scaffoldKey,
      // 添加抽屉组件
      drawer: _buildDrawer(),
      onDrawerChanged: (isOpened) {
        if (isOpened) {
          overlayController.hide();
        } else {
          overlayController.show(0);
        }
      },
      appBar: AppBar(
        leading: _buildLeading(context),
        title: _buildTitle(),
        actions: [
          _buildActions(),
        ],
      ),
      body: BottomPlayerBox(
        child: Column(
          children: [
            Expanded(
              child: PageView(
                controller: _pageController,
                onPageChanged: (index) {
                  setState(() => _currentIndex = index);
                },
                children: _pages,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建抽屉组件
  Widget _buildDrawer() {
    const imageUrl =
        'https://p2.music.126.net/fM7vC38wA8N_EK7zMSHfpw==/109951170529173799.jpg';
    return Drawer(
      width: MediaQuery.of(context).size.width * 0.85, // 设置宽度为屏幕宽度的90%
      shape: const RoundedRectangleBorder(
        // 去除圆角
        borderRadius: BorderRadius.zero,
      ),
      child: SizedBox(
        height: double.infinity,
        child: Column(
          children: [
            // 顶部用户信息
            Container(
              padding: const EdgeInsets.only(
                top: 60,
                bottom: 20,
                left: 16,
                right: 16,
              ),
              decoration: const BoxDecoration(
                color: Colors.black87,
              ),
              child: Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(28),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                        Future.delayed(
                          const Duration(milliseconds: 300),
                          () {
                            // 0.3秒后执行的代码
                            Get.toNamed(
                              '/person',
                              arguments: {
                                'id': 12,
                                'name': '永远的17岁_CrXu',
                              },
                            );
                          },
                        );
                      },
                      child: const MyCachedNetworkImage(
                        imageUrl: imageUrl,
                        width: 56,
                        height: 56,
                        x: 192,
                        y: 192,
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '永远的17岁_CrXu',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                        const SizedBox(height: 4),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white10,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: const Text(
                            'Lv.6',
                            style: TextStyle(color: Colors.white, fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                  ),
                  OutlinedButton(
                    onPressed: () {},
                    style: OutlinedButton.styleFrom(
                      side: const BorderSide(color: Colors.white),
                      foregroundColor: Colors.white,
                      textStyle: const TextStyle(fontSize: 12),
                    ),
                    child: const Text('签到'),
                  ),
                ],
              ),
            ),

            // 中间菜单项
            Expanded(
              child: Container(
                height: double.infinity,
                color: Theme.of(context).scaffoldBackgroundColor,
                child: Column(
                  children: [
                    BuildItem(
                      icon: Icons.mail_outline,
                      title: '我的消息',
                      badge: '33',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.shopping_cart_outlined,
                      title: '积分商城',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.card_membership_outlined,
                      title: '会员中心',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.wifi_tethering_outlined,
                      title: '在线试听免流量',
                      label: '免费试用',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.music_note_outlined,
                      title: '听歌识曲',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.palette_outlined,
                      title: '主题换肤',
                      label: '自选颜色',
                      ontap: () {
                        Navigator.pop(context);
                        Future.delayed(
                          const Duration(milliseconds: 300),
                          () {
                            // 0.3秒后执行的代码
                            Get.toNamed(
                              '/themeChange',
                            );
                          },
                        );
                      },
                    ),
                    BuildItem(
                      icon: Icons.nightlight_outlined,
                      title: '夜间模式',
                      trailing: Transform.scale(
                        scale: 0.6,
                        child: GetBuilder<ThemeController>(
                          builder: (controller) => CupertinoSwitch(
                            value: controller.isDarkMode,
                            onChanged: (val) => controller.toggleTheme(),
                            activeColor: Theme.of(context).primaryColor,
                            trackColor: Theme.of(context)
                                .extension<CustomColors>()!
                                .borderColor,
                          ),
                        ),
                      ),
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.timer_outlined,
                      title: '定时停止播放',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.alarm_outlined,
                      title: '音乐闹钟',
                      ontap: () {},
                    ),
                    BuildItem(
                      icon: Icons.cloud_outlined,
                      title: '我的音乐云盘',
                      ontap: () {},
                    ),
                  ],
                ),
              ),
            ),

            // 底部操作项
            Container(
              height: 60,
              color: Theme.of(context).extension<CustomColors>()!.secondbg,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  TextButton(
                    onPressed: () {},
                    child: Text(
                      '设置',
                      style: Theme.of(context).textTheme.bodyLarge,
                    ),
                  ),
                  TextButton(
                    onPressed: () {},
                    child: Text(
                      '退出应用',
                      style: Theme.of(context).textTheme.bodyLarge,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActions() {
    return IconButton(
      onPressed: () {
        Get.toNamed('/search');
      },
      icon: Icon(
        Icons.search,
        color: Theme.of(context).extension<CustomColors>()!.iconColor,
        size: 28,
      ),
    );
  }

  Widget _buildLeading(BuildContext context) {
    return Builder(
      builder: (innerContext) => SizedBox(
        child: Stack(
          children: [
            Align(
              alignment: Alignment.center,
              child: IconButton(
                onPressed: () {
                  // showCustomDrawer(context);
                  // 打开抽屉
                  _scaffoldKey.currentState?.openDrawer();
                },
                icon: BadgeIcon(
                  badgeColor: Colors.white,
                  textColor: Colors.red,
                  icon: Icon(
                    Icons.menu,
                    size: 28,
                    color:
                        Theme.of(context).extension<CustomColors>()!.iconColor,
                  ),
                  count: 3,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTitle() {
    return SizedBox(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            onPressed: () {
              _pageController.animateToPage(
                0,
                duration: const Duration(microseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            icon: Icon(
              MyFlutterApp.myicon,
              size: 28,
              color:
                  _currentIndex == 0 ? Colors.white : const Color(0x80FFFFFF),
            ),
          ),
          const SizedBox(
            width: 12,
          ),
          IconButton(
            onPressed: () {
              _pageController.animateToPage(
                1,
                duration: const Duration(microseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            icon: Icon(
              MyMusicIcon.myMusicIcon,
              size: 28,
              color:
                  _currentIndex == 1 ? Colors.white : const Color(0x80FFFFFF),
            ),
          ),
          const SizedBox(
            width: 12,
          ),
          IconButton(
            onPressed: () {
              _pageController.animateToPage(
                2,
                duration: const Duration(microseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            icon: Icon(
              TwoPerson.twoPerson,
              size: 28,
              color:
                  _currentIndex == 2 ? Colors.white : const Color(0x80FFFFFF),
            ),
          ),
        ],
      ),
    );
  }
}
